
from flask import Flask, request, send_file
import os
import tempfile
import subprocess

app = Flask(__name__)

@app.route('/convert', methods=['POST'])
def convert_file():
    if 'file' not in request.files:
        return "No file uploaded", 400
    
    file = request.files['file']
    if file.filename == '':
        return "Empty filename", 400
    
    temp_dir = tempfile.mkdtemp()
    input_path = os.path.join(temp_dir, file.filename)
    base_name = os.path.splitext(file.filename)[0]
    expected_output = f"{base_name}.txt"
    output_path = os.path.join(temp_dir, expected_output)
    
    try:
        file.save(input_path)
        cmd = ['libreoffice', '--headless', '--convert-to', 'txt:Text', 
               '--outdir', temp_dir, input_path]
        subprocess.run(cmd, check=True)
        
        if not os.path.exists(output_path):
            raise FileNotFoundError(f"Expected output {expected_output} not found")
            
        with open(output_path, 'r', encoding='utf-8') as f:
            return f.read()
            
    except subprocess.CalledProcessError as e:
        return f"LibreOffice conversion failed: {str(e)}", 500
    except Exception as e:
        return f"Error: {str(e)}", 500
    finally:
        for f in os.listdir(temp_dir):
            try:
                os.remove(os.path.join(temp_dir, f))
            except:
                pass
        os.rmdir(temp_dir)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=9090)

